package com.zzp.gaoji;

public class TestPC {

    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        Productor p = new Productor(synContainer);
        Consumer c = new Consumer(synContainer);
        p.start();
        c.start();
    }
}
//生产者
class Productor extends Thread {

    SynContainer container;
    public Productor(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了第" + i + "只鸡");
        }
    }
}

//消费者
class Consumer extends Thread {
    SynContainer container;
    public Consumer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第" + container.pop().id + "只鸡");
        }
    }
}
//产品
class Chicken {
    //产品编号
    int id;

    public Chicken() {}
    public Chicken(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer {
    Chicken[] chicks = new Chicken[10];

    int count = 0;

    //生产者
    public synchronized void push(Chicken chicken) {
        if (count >= chicks.length){
            //通知消费者消费，生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        //如果没有满，就需要丢入产品
        chicks[count] = chicken;
        count ++;

        //可以通知消费者消费
        this.notifyAll();

    }

    //消费者
    public synchronized Chicken pop() {
        if (count <= 0){
            //等待生产者生产，消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        //如果可以消费，则消费
        count --;
        Chicken chicken = chicks[count];

        //通知生产者生产
        this.notifyAll();
        return chicken;
    }



}


